<script setup>
import { ref, onMounted } from 'vue'
import ChatInterface from '../components/ChatInterface.vue'
import FloatingEmojis from '../components/FloatingEmojis.vue'
import ChatRoomHistory from '../components/ChatRoomHistory.vue'
import { connectToTravelGuideSSE, stopChat } from '../services/api'

const chatInterface = ref(null)
const chatId = ref('')
const sseConnection = ref(null)
const isGenerating = ref(false)

// 生成随机房间ID
const generateRoomId = () => {
  return 'travel_' + Math.random().toString(36).substring(2, 15)
}

// 初始化房间ID（优先使用 localStorage 中的值）
const initRoomId = () => {
  const savedId = localStorage.getItem('deviceRoomId_travel')
  if (savedId) {
    chatId.value = savedId
  } else {
    chatId.value = generateRoomId()
    localStorage.setItem('deviceRoomId_travel', chatId.value)
  }
}

const updateChatId = (newId) => {
  chatId.value = newId
  localStorage.setItem('deviceRoomId_travel', newId)
  // 清空当前聊天记录
  chatInterface.value.chatMessages = []
  // 添加新的欢迎消息
  setTimeout(() => {
    chatInterface.value.addAiMessage('你好！我是AI旅游攻略专家，很高兴能和你聊天。有什么旅游规划或目的地推荐需要咨询吗？')
    chatInterface.value.completeAiMessage()
  }, 500)
}

// 发送消息到后端
const sendMessage = (message) => {
  // 如果有活跃连接，先关闭
  if (sseConnection.value) {
    sseConnection.value.close()
  }
  isGenerating.value = true
  // 连接到SSE
  sseConnection.value = connectToTravelGuideSSE(
    message,
    chatId.value,
    // 消息回调 - 处理流式响应
    (data) => {
      chatInterface.value.addAiMessage(data)
    },
    // 完成回调
    () => {
      chatInterface.value.completeAiMessage()
      isGenerating.value = false
      sseConnection.value = null
    }
  )
}

const stopGeneration = async () => {
  if (sseConnection.value) {
    sseConnection.value.close()
    sseConnection.value = null
  }
  await stopChat(chatId.value)
  chatInterface.value.completeAiMessage()
  isGenerating.value = false
}

onMounted(() => {
  initRoomId()
  // 添加欢迎消息
  setTimeout(() => {
    chatInterface.value.addAiMessage('你好！我是AI旅游攻略专家，很高兴能和你聊天。有什么旅游规划或目的地推荐需要咨询吗？')
    chatInterface.value.completeAiMessage()
  }, 500)
})
</script>

<template>
  <div class="chat-container">
    <FloatingEmojis />
    <ChatRoomHistory
      :currentRoomId="chatId"
      @select-room="updateChatId"
      type="travel"
    />
    <ChatInterface
      ref="chatInterface"
      title="AI 旅游攻略专家"
      :chatId="chatId"
      userAvatar="👤"
      aiAvatar="🌍"
      @send-message="sendMessage"
      :isGenerating="isGenerating"
      :onStop="stopGeneration"
      @update-chat-id="updateChatId"
    />
    

  </div>
</template>

<style scoped>
.chat-container {
  position: relative;
  height: 100%;
  overflow: hidden;
  background-color: var(--bg-color);
}

/* 历史记录按钮样式 */
.history-button {
  position: fixed;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(30, 30, 40, 0.9);
  border: 1px solid rgba(0, 243, 255, 0.2);
  border-radius: 20px;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 100;
}

.history-button:hover {
  background: rgba(40, 40, 50, 0.95);
  border-color: var(--neon-blue);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 243, 255, 0.2);
}

.history-icon {
  width: 20px;
  height: 20px;
  color: var(--neon-blue);
  transition: transform 0.3s ease;
}

.history-button:hover .history-icon {
  transform: rotate(15deg);
}

@media (max-width: 768px) {
  .history-button {
    padding: 6px 12px;
    font-size: 14px;
  }
  
  .history-icon {
    width: 16px;
    height: 16px;
  }
}
</style>